<script>
import { ref, reactive, computed } from 'vue'
import { onClickOutside } from '@vueuse/core'
import axios from 'axios'
export default {
  name: 'CitySelector',
  props: {
    location: { type: String, default: '' }
  },
  setup (props, { emit }) {
    // 定义一个用于控制城市选择器显示状态的响应式变量
    const visible = ref(false)
    // 打开城市选择器并获取城市数据
    const openCity = () => {
      visible.value = true //设置选择器可见
      //如果全局对象中已有城市数据，则直接使用
      if (window.cityData) {
        cityData.value = window.cityData
      }

      //否则通过API获取城市数据
      else {
        getCityData().then(res => {
          cityData.value = res.data
          window.cityData = res.data //将数据存储到全局对象中
        })
      }
      //清空选择结果
      for (const key in changeResult) {
        changeResult[key] = ''
      }
    }
    // 关闭城市选择器
    const closeCity = () => {
      visible.value = false
    }
    // 切换城市选择器的显示状态
    const toggleCity = () => {
      visible.value ? closeCity() : openCity()
    }
    // 监听点击事件，如果点击发生在目标元素外部，则关闭城市选择器
    const target = ref(null)
    onClickOutside(target, () => closeCity())
    // 存储城市数据
    const cityData = ref([])
    // 城市数据的请求url
    const url = 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
    // 获取城市数据
    const getCityData = () => {
      return axios({ url })
    }
    // 存储选择的城市信息
    const changeResult = reactive({
      provinceCode: '',
      provinceName: '',
      cityCode: '',
      cityName: '',
      countyCode: '',
      countyName: '',
      location: ''
    })
    // 更新选择的城市信息
    const changeItem = item => {
      if (item.level === 0) {
        changeResult.provinceName = item.name
        changeResult.provinceCode = item.code
      }
      if (item.level === 1) {
        changeResult.cityName = item.name
        changeResult.cityCode = item.code
      }
      if (item.level === 2) {
        changeResult.countyCode = item.code
        changeResult.countyName = item.name
        changeResult.location = `${changeResult.provinceName} ${changeResult.cityName} ${changeResult.countyName}`
        emit('change', changeResult)
        closeCity()
      }
    }
    // 计算当前的城市列表
    const curList = computed(() => {
      let curList = cityData.value
      if (changeResult.provinceCode) {
        curList = curList.find(it => it.code === changeResult.provinceCode).areaList
      }
      if (changeResult.cityCode) {
        curList = curList.find(it => it.code === changeResult.cityCode).areaList
      }
      return curList
    })
    return { visible, toggleCity, target, cityData, changeResult, changeItem, curList }
  }
}
</script>

<template>
  <div class="city-selector" ref="target">
    <div class="select" @click="toggleCity" :class="{ active: visible }">
      <span class="placeholder" v-if="changeResult.location == '' && location == ''"
        >请选择配送地址</span
      >

      <span class="value" v-else>
        {{ changeResult.location ? changeResult.location : location }}
      </span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-show="visible">
      <span class="ellipsis" @click="changeItem(item)" v-for="item in curList" :key="item.code">
        {{ item.name }}
      </span>
    </div>
  </div>
</template>

<style scoped lang="less">
@font-face {
  font-family: 'iconfont';
  src: url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.eot'); /* IE9 */
  src: url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.eot#iefix') format('embedded-opentype'),
    url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.woff2') format('woff2'),
    url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.woff') format('woff'),
    url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.ttf') format('truetype'),
    url('//at.alicdn.com/t/font_2143783_iq6z4ey5vu.svg#iconfont') format('svg');
}

.iconfont {
  font-family: 'iconfont' !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
.icon-angle-down:before {
  content: '\e7b5';
}
.city-selector {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
